package com.dmtt.web.are.service.impl;

import com.dmtt.util.EnumStatus;
import com.dmtt.util.PageManager;
import com.dmtt.util.Response;
import com.dmtt.web.are.entity.*;
import com.dmtt.web.are.service.AreSynchronizedService;
import com.dmtt.web.are.vo.*;
import com.dmtt.web.common.Constant;
import com.dmtt.web.entity.User;
import com.dmtt.web.mapper.AreSynchronizedMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author guzhenbiao
 * @project dmtt
 * @package com.dmtt.web.are.service.impl
 * @className AreSynchronizedServiceImpl
 * @description TODO
 * @since2022/8/6 12:51
 * @version1.0
 */
@Service
public class AreSynchronizedServiceImpl implements AreSynchronizedService {

    @Autowired
    private AreSynchronizedMapper areSynchronizedMapper;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * @Description: 区域锁的列表加分页
     * @param:[currentPage, limit, areName, currAgvName]
     * @return: com.dmtt.util.Response
     * @Author: guzhenbiao
     * @Date: 2022-08-220 08:53:33
     */
    @Override
    public Response queryAreSynchronizedByPage(QueryParamsVo queryParamsVo) {
        Response response = new Response();
        PageManager page = new PageManager();
        String agvName = queryParamsVo.getAgvName();
        String areName = queryParamsVo.getAreName();
        int currentPage = Integer.parseInt(queryParamsVo.getCurrentPage());
        int limit = Integer.parseInt(queryParamsVo.getLimit());
        try {
            if(currentPage ==0 && limit ==0){
                response.setState(EnumStatus.FAIL);
                response.setMessage("参数错误，请重新设置当前页以及每页显示的个数！");
                response.setResponseText(null);
                return response;
            }
            page.setCurrentPage(currentPage);
            page.setLimit(limit);
            int currentStartIndex = (page.getCurrentPage() - 1) * page.getLimit();
            AreSynchronized areSynchronized = new AreSynchronized();
            areSynchronized.setAreName(areName);
            areSynchronized.setCurrAgvName(agvName);
            List<AreSynchronized> areSynchronizedList = areSynchronizedMapper.queryAreSynchronizedByPage(areSynchronized,currentStartIndex,limit);
            Integer areSynchronizedCount = areSynchronizedMapper.queryAreSynchronizedForCount(areSynchronized,currentStartIndex,limit);
            page.setRoot(areSynchronizedList);
            page.setTotal(areSynchronizedCount);
            response.setState(EnumStatus.SUCCESS);
            response.setMessage("查询区域锁的列表加分页成功");
            response.setResponseText(page);
        }catch (Exception e){
            e.printStackTrace();
            response.setState(EnumStatus.FAIL);
            response.setMessage("查询区域锁的列表加分页失败");
            response.setResponseText(page);
        }
        return response;
    }

    /**
     * @Description: 区域锁新增
     * @param:[areSynchronizedVo, user]
     * @return: Response
     * @Author: guzhenbiao
     * @Date: 2022-08-218 13:44:05
     */
    @Transactional
    @Override
    public Response insertAreSynchronized(AreSynchronizedVo areSynchronizedVo, User user) {
        Response response = new Response();
        try{
            AreSynchronized areSynchronized = areSynchronizedVo.getAreSynchronized();
            List<AgvCoordinate> agvCoordinateList = areSynchronizedVo.getAgvCoordinateList();
            Long areSynchronizedId = this.insertAreSynchronized(areSynchronized, user);
            this.insertAgvCoordinate(agvCoordinateList,user,areSynchronizedId);
            AreSynchronizedPointVo areSynchronizedPointVo = null;
            for (AgvCoordinate agvCoordinate : agvCoordinateList){
                if(agvCoordinate.getCompany().equals(Constant.COMPANY_CODE_JIASHUN)){
                    //同步到新车方
                    areSynchronizedPointVo = this.encapsulationData(String.valueOf(areSynchronizedId), agvCoordinate.getCompany());
                    ResponseEntity<ResultCode> result = restTemplate.postForEntity(Constant.JIA_SHUN_URL, areSynchronizedPointVo, ResultCode.class);
                   if(!result.getBody().getRecCode().equals(Constant.REC_CODE)){
                       response.setState(EnumStatus.FAIL);
                       response.setMessage("新增失败！ 远程服务无法连接");
                       response.setResponseText(areSynchronizedVo);
                       TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                       return response;
                   }
                }
            }
            response.setState(EnumStatus.SUCCESS);
            response.setMessage("新增成功！");
            response.setResponseText(areSynchronizedVo);
        }catch (Exception e){
            e.printStackTrace();
            response.setState(EnumStatus.FAIL);
            response.setMessage("新增失败！服务异常");
            response.setResponseText(areSynchronizedVo);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return response;
    }

    /**
     * @Description: 区域锁编辑
     * @param:[areSynchronizedVo, user]
     * @return: Response
     * @Author: guzhenbiao
     * @Date: 2022-08-218 13:44:09
     */
    @Transactional
    @Override
    public Response updateAreSynchronized(AreSynchronizedVo areSynchronizedVo, User user) {
        Response response = new Response();
        try {
            AreSynchronized areSynchronized = areSynchronizedVo.getAreSynchronized();
            AreSynchronized areSynchronizedOld = areSynchronizedMapper.getAreSynchronizedById(String.valueOf(areSynchronized.getId()));
            if(areSynchronizedOld.getLockStatus() == Constant.ZERO){
                List<AgvCoordinate> agvCoordinateList = areSynchronizedVo.getAgvCoordinateList();
                this.updateAreSynchronized(areSynchronized, user);
                this.insertAgvCoordinate(agvCoordinateList,user,areSynchronized.getId());
                AreSynchronizedPointVo areSynchronizedPointVo = null;
                for (AgvCoordinate agvCoordinate : agvCoordinateList){
                    if(agvCoordinate.getCompany().equals(Constant.COMPANY_CODE_JIASHUN)){
                        //同步到新车方
                        areSynchronizedPointVo = this.encapsulationData(String.valueOf(areSynchronized.getId()), agvCoordinate.getCompany());
                        ResponseEntity<ResultCode> result = restTemplate.postForEntity(Constant.JIA_SHUN_URL, areSynchronizedPointVo, ResultCode.class);
                        if(!result.getBody().getRecCode().equals(Constant.REC_CODE)){
                            response.setState(EnumStatus.FAIL);
                            response.setMessage("编辑失败！ 远程服务无法连接");
                            response.setResponseText(areSynchronizedVo);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return response;
                        }
                    }
                }
                response.setState(EnumStatus.SUCCESS);
                response.setMessage("编辑成功");
                response.setResponseText(areSynchronizedVo);
            }else{
                response.setState(EnumStatus.FAIL);
                response.setMessage("此区域已上锁,禁止编辑！");
                response.setResponseText(areSynchronizedOld);
            }
        }catch (Exception e){
            e.printStackTrace();
            response.setState(EnumStatus.FAIL);
            response.setMessage("编辑失败! 服务异常");
            response.setResponseText(null);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return response;
    }

    /**
     * @Description: 区域锁禁用
     * @param:[id, user]
     * @return: Response
     * @Author: guzhenbiao
     * @Date: 2022-08-218 13:44:13
     */
    @Override
    public Response disableAreSynchronizedById(QueryParamsVo queryParamsVo, User user) {
        Response response = new Response();
        String id = queryParamsVo.getId();
        String status = queryParamsVo.getStatus();
        try {
            if(StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(status)){
                boolean flag = Integer.parseInt(status) == Constant.ZERO;
                String str = flag ? "禁用" : "启用";
                if(flag){
                    AreSynchronized areSynchronized = areSynchronizedMapper.getAreSynchronizedById(id);
                    if(areSynchronized.getLockStatus() == Constant.ONE){
                        response.setState(EnumStatus.FAIL);
                        response.setMessage("此区域已上锁,禁止禁用！");
                        response.setResponseText(areSynchronized);
                        return response;
                    }
                    List<AgvSuspend> agvSuspendList = areSynchronizedMapper.getAgvSuspendByAreSynchronizedIdAndStatus(id, String.valueOf(Constant.ONE));
                    if(agvSuspendList.size() > Constant.ZERO){
                        response.setState(EnumStatus.FAIL);
                        response.setMessage("此区域有车在等待,禁止禁用！");
                        response.setResponseText(areSynchronized);
                        return response;
                    }
                }
                areSynchronizedMapper.updateAreSynchronizedForStatusById(id,status);
                List<AgvCoordinate> agvCoordinateList = areSynchronizedMapper.getAgvCoordinateListByAreSynchronizedId(id);
                AreSynchronizedPointVo areSynchronizedPointVo = null;
                for (AgvCoordinate agvCoordinate : agvCoordinateList){
                    if(agvCoordinate.getCompany().equals(Constant.COMPANY_CODE_JIASHUN)){
                        //同步到新车方
                        areSynchronizedPointVo = this.encapsulationData(String.valueOf(id), agvCoordinate.getCompany());
                        ResponseEntity<ResultCode> result = restTemplate.postForEntity(Constant.JIA_SHUN_URL, areSynchronizedPointVo, ResultCode.class);
                        if(!result.getBody().getRecCode().equals(Constant.REC_CODE)){
                            response.setState(EnumStatus.FAIL);
                            response.setMessage(str+"失败！ 远程服务无法连接");
                            response.setResponseText(null);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return response;
                        }
                    }
                }
                response.setState(EnumStatus.SUCCESS);
                response.setMessage(str + "成功");
                response.setResponseText(null);
            }
        }catch (Exception e){
            e.printStackTrace();
            response.setState(EnumStatus.FAIL);
            response.setMessage("禁用失败! 服务异常");
            response.setResponseText(null);
        }
        return response;
    }

    /**
     * @Description: 区域锁查看
     * @param:[id]
     * @return: Response
     * @Author: guzhenbiao
     * @Date: 2022-08-218 13:44:16
     */
    @Override
    public Response getAreSynchronizedById(QueryParamsVo queryParamsVo) {
        Response response = new Response();
        try {
            if(StringUtils.isNotEmpty(queryParamsVo.getId())){
                AreSynchronizedVo areSynchronizedVo = new AreSynchronizedVo();
                AreSynchronized areSynchronized = areSynchronizedMapper.getAreSynchronizedById(queryParamsVo.getId());
                List<AgvCoordinate> agvCoordinateList = areSynchronizedMapper.getAgvCoordinateListByAreSynchronizedId(queryParamsVo.getId());
                areSynchronizedVo.setAreSynchronized(areSynchronized);
                areSynchronizedVo.setAgvCoordinateList(agvCoordinateList);
                response.setState(EnumStatus.SUCCESS);
                response.setMessage("查看成功");
                response.setResponseText(areSynchronizedVo);
            }
        }catch (Exception e){
            e.printStackTrace();
            response.setState(EnumStatus.FAIL);
            response.setMessage("查看失败!");
            response.setResponseText(null);
        }
        return response;
    }

    /**
     * @Description: 获取区域锁历史信息列表加分页
     * @param:[currentPage, limit, areName, currAgvName]
     * @return: com.dmtt.util.Response
     * @Author: guzhenbiao
     * @Date: 2022-08-220 15:43:57
     */
    @Override
    public Response queryAreSynchronizedHistoryByPage(QueryParamsVo queryParamsVo) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Response response = new Response();
        String agvName = queryParamsVo.getAgvName();
        Long areSynchronizedId = Long.parseLong(queryParamsVo.getId());
        try {
            AreSynchronizedHistory areSynchronizedHistory = new AreSynchronizedHistory();
            Date inDate = (queryParamsVo.getInDate() == null || queryParamsVo.getInDate().equals("") ) ? null:format.parse(queryParamsVo.getInDate());
            Date outDate = (queryParamsVo.getOutDate() == null || queryParamsVo.getOutDate().equals("")) ? null:format.parse(queryParamsVo.getOutDate());
            areSynchronizedHistory.setInDate(inDate);
            areSynchronizedHistory.setOutDate(outDate);
            areSynchronizedHistory.setAreSynchronizedId(areSynchronizedId);
            areSynchronizedHistory.setAgvName(agvName);
            List<AreSynchronizedHistory> areSynchronizedHistoryList = areSynchronizedMapper.queryAreSynchronizedHistoryByPage(areSynchronizedHistory);
            response.setState(EnumStatus.SUCCESS);
            response.setMessage("查询区域锁历史的列表加分页成功");
            response.setResponseText(areSynchronizedHistoryList);
        }catch (Exception e){
            e.printStackTrace();
            response.setState(EnumStatus.FAIL);
            response.setMessage("查询区域锁历史的列表加分页失败");
            response.setResponseText(null);
        }
         return response;
    }

    /**
     * @Description: 获取agv供应商集合
     * @param:[]
     * @return: com.dmtt.util.Response
     * @Author: guzhenbiao
     * @Date: 2022-08-227 09:15:59
     */
    @Override
    public Response getAgvCompanyList() {
        Response response = new Response();
        try {
            List<CompanyVo> companyVoList = areSynchronizedMapper.getAgvCompanyList();
            response.setState(EnumStatus.SUCCESS);
            response.setMessage("查询小车成功");
            response.setResponseText(companyVoList);
        }catch (Exception e){
            e.printStackTrace();
            response.setState(EnumStatus.FAIL);
            response.setMessage("查询小车失败!");
            response.setResponseText(null);
        }
        return response;
    }


    /**
     * @Description: 新增区域锁数据
     * @param:[areSynchronized, user]
     * @return: java.lang.Long
     * @Author: guzhenbiao
     * @Date: 2022-08-218 15:49:01
     */
    public Long insertAreSynchronized(AreSynchronized areSynchronized, User user){
        areSynchronized.setLockStatus(Constant.ZERO);
        areSynchronized.setStatus(Constant.ONE);
        areSynchronized.setCreateUser(user.getId());
        areSynchronized.setCreateDate(new Date());
        areSynchronizedMapper.insertAreSynchronized(areSynchronized);
        return areSynchronized.getId();
    }

    /**
     * @Description: 编辑区域锁数据
     * @param:[areSynchronized, user]
     * @return: java.lang.Long
     * @Author: guzhenbiao
     * @Date: 2022-08-218 16:10:05
     */
    public void updateAreSynchronized(AreSynchronized areSynchronized, User user){
        areSynchronized.setUpdateUser(user.getId());
        areSynchronized.setUpdateDate(new Date());
        areSynchronizedMapper.updateAreSynchronized(areSynchronized);
    }

    /**
     * @Description: 新增坐标表数据，不过新增之前先做删除
     * @param:[agvCoordinateList, user, areSynchronizedId]
     * @return: void
     * @Author: guzhenbiao
     * @Date: 2022-08-218 15:49:08
     */
    public void insertAgvCoordinate(List<AgvCoordinate> agvCoordinateList, User user, Long areSynchronizedId){
        areSynchronizedMapper.deleteAgvCoordinateByAreSynchronizedId(areSynchronizedId);
        agvCoordinateList.forEach(current->{
            current.setAreSynchronizedId(areSynchronizedId);
            current.setCreateUser(user.getId());
            current.setCreateDate(new Date());
            areSynchronizedMapper.insertAgvCoordinate(current);
        });
    }



    /**
     * @Description: 封装数据
     * @param:[areSynchronizedId, companyCode]
     * @return: com.dmtt.web.are.vo.AreSynchronizedPointVo
     * @Author: guzhenbiao
     * @Date: 2022-08-224 17:42:29
     */
    public AreSynchronizedPointVo encapsulationData(String areSynchronizedId, String companyCode){
        AgvCoordinate agvCoordinate = areSynchronizedMapper.getAgvCoordinateListByAreSynchronizedIdAndCompany(areSynchronizedId, companyCode);
        AreSynchronizedPointVo areSynchronizedPointVo = new AreSynchronizedPointVo();
        AreSynchronized areSynchronized = areSynchronizedMapper.getAreSynchronizedById(areSynchronizedId);
        areSynchronizedPointVo.setId(String.valueOf(areSynchronized.getId()));
        areSynchronizedPointVo.setAreName(areSynchronized.getAreName());
        areSynchronizedPointVo.setArePointList(areSynchronized.getArePointList());
        areSynchronizedPointVo.setArePointArray(agvCoordinate.getArePointList());
        areSynchronizedPointVo.setArrLength(areSynchronized.getArrLength());
        areSynchronizedPointVo.setArrWide(areSynchronized.getArrWide());
        areSynchronizedPointVo.setStatus(String.valueOf(areSynchronized.getStatus()));
        return areSynchronizedPointVo;
    }
}
